<template>
  <view class="container">
    <custom-navbar backText="销售单详情" @back="goBack" :immersive="true"></custom-navbar>
    <view class="container_header" :style="{ paddingTop: `${navbarHeight}px` }">
      <!-- <uni-nav-bar
        backgroundColor="transparent"
        :border="false"
        leftWidth="300rpx"
        @clickLeft="back"
        style="z-index: 999"
      >
        <view slot="left" style="display: flex; align-items: center">
          <uni-icons size="22" type="left" />
          <view style="font-size: 36rpx">销售单详情</view>
        </view>
      </uni-nav-bar> -->

      <view class="container_header_customer">
        <view class="container_header_customer_select">
          <view class="container_header_customer_select_label">客户</view>
          <view class="container_header_customer_select_line">|</view>

          <picker
            :disabled="ifDetil"
            :value="customer_index"
            :range="customerList"
            class="input"
            :range-key="'name'"
            @change="bindPickerChangess($event)"
          >
            <input
              v-if="!ifDetil"
              :disabled="ifDetil"
              class="container_header_customer_select_input"
              type="text"
              disabled
              placeholder="请选择客户"
              v-model="customerName"
            />
            <span v-else style="margin-right: 60px; margin-left: 10px">{{
              params["customerName"]
            }}</span>
          </picker>
        </view>
        <button class="container_header_customer_add" @click="add">新增</button>
      </view>
    </view>
    <view class="container_main">
      <scroll-view class="container_main_scroll" :scroll-y="true">
        <view class="container_main_scroll_list">
          <saleForm
            :disabled="ifDetil"
            v-for="(item, index) in detailList"
            :key="index"
            class="container_main_scroll_list_item"
            :formInfo="item"
            :index="index"
            @inputChange="inputChange"
            @uploadChange="uploadChange"
          ></saleForm>
        </view>
      </scroll-view>
    </view>
    <view class="container_footer">
      <button class="container_footer_cancel" @click="back">取消</button>
      <button class="container_footer_submit" @click="submit">确认</button>
    </view>
  </view>
</template>

<script>
import { updateSale, saleList } from "@/api/home.js";
import { customerLists } from "@/api/public.js";
import saleForm from "@/components/saleForm.vue";
import navbarMixin from "@/mixins/navbar.js";

export default {
  components: {
    saleForm,
  },
  mixins: [navbarMixin],
  data() {
    return {
      detailList: [],
      params: {
        code: "",
        busDate: null,
        customerId: null,
        userId: null,
        orderStatus: null,
        remark: null,
        createUserId: null,
        createUserName: null,
        createTime: null,
        updateUserId: null,
        updateUserName: null,
        updateTime: null,
        closeUserId: null,
        closeUserName: null,
        closeTime: null,
        auditUserId: null,
        auditUserName: null,
        auditTime: null,
        statementDate: null,
        keyword: null,
        startTime: null,
        endTime: null,
        customerName: "",
        customerAreaName: null,
        customerTypeName: null,
        userName: "",
        detailList: "",
        detailCount: null,
        detailProductNum: null,
      },
      customerIndex: -1,
      customerList: [],
      ifDetil: false,
      customerName: "",
    };
  },
  onLoad(option) {
    this.ifDetil = option.item ? true : false;
    console.log(this.ifDetil);
    if (option.item) {
      //修改
      const item = JSON.parse(decodeURIComponent(option.item));
      this.getDetail(item.id);
    } else {
      //新增
      this.add();
    }
    this.getCustomerList();
  },
  methods: {
    getDetail(id) {
      if (this.isLoading) return;

      uni.showLoading({
        title: "加载中",
      });
      saleList({
        id: id,
      })
        .then((res) => {
          uni.hideLoading();

          if (res.content.length > 0) {
            const info = res.content[0];
            console.log("mould---------" + JSON.stringify(info));
            this.params = info;
            this.detailList = JSON.parse(info.detailList);
          }
        })
        .catch((e) => {
          uni.hideLoading();

          uni.showToast({
            title: e.msg,
            icon: "none",
          });
        });
    },
    inputChange(data) {
      if (data) {
        const index = data.index;

        this.detailList.splice(index, 1, data.data);
      }
    },
    uploadChange(data) {
      console.log("data" + JSON.stringify(data));
      if (data) {
        const index = data.index;
        let info = this.detailList[index];
        info.designImage = data.url;
        this.detailList.splice(index, 1, info);
      }
    },
    add() {
      if (this.ifDetil) {
        return;
      }
      //新增一个名称
      const formInfo = {
        boxBarcode: null,
        category: null,
        count: null,
        designImage: null,
        detailRemark: null,
        grammage: null,
        id: null,
        level: null,
        material: null,
        model: null,
        orderCode: null,
        orderId: null,
        productCode: null,
        productId: null,
        productName: null,
        productTypeId: null,
        productTypeName: null,
        saleTaxPrice: null,
        screwMouth: null,
        unitId: null,
        unitName: null,
      };
      this.detailList.push(formInfo);
    },
    bindPickerChangess: function (e) {
      console.log("e", e);
      this.customerIndex = e.target.value;
      this.params.customerId = this.customerList[this.customerIndex].id;
      this.params.customerName = this.customerList[this.customerIndex].name;
      this.customerName = this.params.customerName;
    },
    getCustomerList() {
      customerLists({
        size: 999,
      }).then((res) => {
        res.content.forEach((item) => this.customerList.push(item));

        for (var i = 0; i < this.customerList.length; i++) {
          if (this.customerList[i].id == this.params.customerId) {
            this.customerIndex = i;
          }
        }
      });
    },
    submit() {
      const that = this;
      if (!that.params.customerId) {
        uni.showToast({
          title: "请选择客户",
          icon: "none",
        });
        return;
      }
    //上传图片必填
      if (!that.detailList) {
        uni.showToast({
          title: "请上传图片",
          icon: "none",
        });
        return;
      }
      let _index = that.detailList.findIndex(
        (item) => !item.designImage
      );
      console.log('_index',_index)
      if (~_index) {
        uni.showToast({
          title: "请上传图片",
          icon: "none",
        });
        return;
      }
      that.params.detailList = JSON.stringify(that.detailList);
      console.log("params" + JSON.stringify(that.params));
      that.params.busDate = new Date();
      uni.showLoading();
      updateSale(that.params)
        .then((res) => {
          uni.hideLoading();
          if (res.status) {
            uni.showToast({
              title: res.msg,
              icon: "none",
            });
          } else {
            const eventChannel = that.getOpenerEventChannel();
            eventChannel.emit("acceptDataFromOpenedPage", {
              data: "",
            });
            uni.navigateBack({
              delta: 1, // 返回的页面数，如果delta大于现有页面数，则返回到首页
            });
          }
          console.log("res" + JSON.stringify(res));
        })
        .catch((e) => {
          uni.hideLoading();

          uni.showToast({
            title: e.msg,
            icon: "none",
          });
        });
    },
    back() {
      uni.navigateBack({
        delta: 1, // 返回的页面数，如果delta大于现有页面数，则返回到首页
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.navbar-text {
  text-align: left;
  /* 设置文字左对齐 */
}

.status_bar {
  height: var(--status-bar-height);
  width: 100%;
}

.container {
  width: 100%;
  height: 100vh;
  background: #f4f5f9;
  display: flex;
  flex-direction: column;

  &_header {
    position: sticky;
    top: 0;
    left: 0;
    right: 0;

    &_customer {
      padding: 10rpx 20rpx;
      border-radius: 10rpx;
      display: flex;
      align-items: center;

      &_select {
        display: flex;
        flex: 1;
        background-color: white;
        padding: 10rpx 20rpx;
        border-radius: 30rpx;

        &_label {
          flex: 1;
        }

        &_line {
          color: #999;
        }

        &_input {
          flex: 3;
          padding-left: 10rpx;
        }
      }

      &_add {
        width: 120rpx;
        height: 60rpx;
        line-height: 60rpx;
        background-color: #1890ff;
        color: white;
        font-size: 28rpx;
        border-radius: 30rpx;
        margin-left: 20rpx;
      }
    }
  }

  &_main {
    flex: 1;
    margin-bottom: 20rpx;
    overflow-y: auto;

    &_scroll {
      height: 100%;

      &_list {
        margin: 20rpx;
      }
    }
  }

  &_footer {
    position: sticky;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    padding: 20rpx;
    background-color: white;

    &_cancel {
      flex: 1;
      height: 80rpx;
      background-color: white;
      border-radius: 50rpx;
      border: 1rpx solid #cbd2de;
      font-size: 32rpx;
      margin-right: 20rpx;
    }

    &_submit {
      flex: 1;
      height: 80rpx;
      background-color: #1890ff;
      color: white;
      border-radius: 50rpx;
      margin-left: 20rpx;
    }
  }
}

button::after {
  border: none;
}
</style>
